import { ProColumnType } from '@ant-design/pro-table';
import { UserCateInfo } from '@/pages/personnelEntry/interface';
import { ProFormCascader } from '@ant-design/pro-form';
import { CascaderOptionType } from 'antd/lib/cascader';

export default function injectCascader<T, K = keyof T>(
    columns: ProColumnType<T>[],
    datas: UserCateInfo | undefined,
    keys: (K | [key: K, value: K])[],
) {
    if (!datas) return columns;
    return columns.map((item) => {
        const index = keys.find(
            // @ts-ignore
            (key) => (Array.isArray(key) ? key[0] : key) === item.key,
        );

        if (Boolean(index)) {
            const keyByIndex = Array.isArray(index) ? index[1] : index;

            // @ts-ignore
            const values = datas[keyByIndex];

            return {
                ...item,
                fieldProps: {
                    ...item.fieldProps,
                    options:
                        transformToOptions(
                            Array.isArray(values) ? values : [],
                        ) || [],
                },
            };
        }
        return item;
    });
}

function transformToOptions(value: UserCateInfo['army']): CascaderOptionType[] {
    return value?.map((item) => ({
        value: item.id,
        label: item.name || '',
        pid: item.pid,
        children: transformToOptions(item.child),
    }));
}
